package com.light.mytext.thread

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.light.mytext.R
import com.light.mytext.lock.SynchronizedDemo
import com.light.mytext.utiles.ToastUtils
import kotlinx.android.synthetic.main.activity_my_thread.*


/**
 * 线程
 */
class MyThreadActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var mLocalBroadcastManager: LocalBroadcastManager
    private lateinit var mBroadcastReceiver: MyBroadcastReceiver


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_thread)
        init_Listener()

        //注册广播--IntentService
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this)
        mBroadcastReceiver = MyBroadcastReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction("action.type.thread")
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter)
    }

    fun init_Listener() {
        bt_0.setOnClickListener(this)
        bt_1.setOnClickListener(this)
        bt_2.setOnClickListener(this)
        bt_3.setOnClickListener(this)
        bt_4.setOnClickListener(this)
        bt_5.setOnClickListener(this)
        bt_6.setOnClickListener(this)
        bt_7.setOnClickListener(this)
    }

    var handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0 -> {
                    tv_statue.text = "下载中"
                    ToastUtils.show(baseContext, "开始下载")
                }
                1 -> {
                    tv_statue.text = "下载完成"
                    ToastUtils.show(baseContext, "下载完成")
                }

            }

        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.bt_0 -> {//Thread
                tv_statue.text = "开始下载"
                Thread{
                    tv_statue.post(Runnable {
                        tv_statue.text = "下载中"
                        ToastUtils.show(baseContext, "下载中")
                    })
                    Thread.sleep(2000)
                    tv_statue.post(Runnable {
                        tv_statue.text = "下载完成"
                        ToastUtils.show(baseContext, "下载完成")
                    })

                }.start()
            }
            R.id.bt_1 -> {//Handler+Thread
                Thread {
                    handler.sendEmptyMessage(0)
                    Thread.sleep(3000)
                    handler.sendEmptyMessage(1)
                }.start()
            }
            R.id.bt_2 -> {//AsyncTask
                var time = 3
                val asyncTask: AsyncTask<Int, Int, String?> =
                    object : AsyncTask<Int, Int, String?>() {
                        override fun doInBackground(vararg params: Int?): String? {
                            for (i in params[0]!! downTo 1) {
                                try {
                                    Thread.sleep(1000)
                                    publishProgress(i) //调用onProgressUpdate方法
                                } catch (e: InterruptedException) {
                                    e.printStackTrace()
                                }
                            }
                            return "计时结束"
                        }

                        override fun onPostExecute(result: String?) {//结束--返回doInBackground里面返回的信息
                            super.onPostExecute(result)
                            tv_statue.text = result
                            Log.i("AsyncTask==","onPostExecute"+result)
                        }

                        override fun onProgressUpdate(vararg values: Int?) {//过程更新
                            super.onProgressUpdate(*values)
                            tv_statue.text = values[0].toString()
                            Log.i("AsyncTask==","onProgressUpdate"+values[0].toString())
                        }
                    }
                asyncTask.execute(time)
            }
            R.id.bt_3 -> {//ThreadPoolExecutor
                val intent = Intent(this, ThreadPoolActivity::class.java)
                startActivity(intent)
            }
            R.id.bt_4 -> {//IntentService
                val intent = Intent(this, MyIntentService::class.java)
                startService(intent)
            }
            R.id.bt_5 -> {//Callable+Future
                val intent = Intent(this, CallableFutureActivity::class.java)
                startActivity(intent)
            }
            R.id.bt_6 -> {//Runnable
                SynchronizedDemo().main()
            }
            R.id.bt_7 -> {//Callable+Future
                val intent = Intent(this, ThreadLocalActivity::class.java)
                startActivity(intent)
            }
        }
    }

    /**
     * 非静态内部类,关键字inner
     *可以访问外部类的成员变量
     */
    inner class MyBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            when (intent.action) {
                "action.type.thread" -> {
                    //更改UI
                    val progress = intent.getIntExtra("progress", 0)
                    tv_statue.text = progress.toString()
                    if (progress == 0) {
                        tv_statue.text = "下载结束"
                    }
                }
            }
        }
    }
}
